<template>
  <!-- <div>pages\systemManagement\userManagement\[id].vue</div> -->
  <!-- <el-main class=""> -->
  <!-- <div class="">
    {{ user.data.value }}
  </div> -->

  <el-form
    v-if="user.data.value"
    :model="user.data.value"
    ref="formRef"
    :rules="rules"
    label-width="80px"
    :inline="false"
    v-loading="user.pending.value"
    label-suffix="："
  >
    <el-form-item label="用户名" prop="name">
      <el-input
        :disabled="props.type === 'edit'"
        v-model="user.data.value.name"
      ></el-input>
    </el-form-item>
    <el-form-item label="角色" prop="roles">
      <role-select v-model="user.data.value.roles" multiple></role-select>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-switch
        v-model="user.data.value.status"
        :active-value="Status.enable"
        :inactive-value="Status.disable"
      />
    </el-form-item>
    <el-form-item>
      <el-button @click="router.back()">取消</el-button>
      <el-button
        type="primary"
        :loading="submit.pending.value"
        @click="onSubmit()"
        >保存</el-button
      >
    </el-form-item>
  </el-form>

  <!-- </el-main> -->
</template>

<script setup lang="ts">
import { Status } from '~~/types/status.d';
import { User } from '~~/types/user.d';
import type { FormInstance, FormRules } from 'element-plus';

interface Props {
  type: 'edit' | 'add';
}

const props = withDefaults(defineProps<Props>(), {
  type: 'edit',
});

const router = useRouter();
const route = useRoute();

const user = useFetchApi(`/system/user/${route.params.uid}`, {
  default: (): User => ({
    // uid: undefined,
    name: '',
    roles: [],
    status: 1,
    // createTime: undefined,
  }),
  immediate: props.type === 'edit',
});
if (props.type === 'add') {
  // user.data.value = {
  //   name: '',
  //   roles: [],
  //   status: 1,
  // };
  user.pending.value = false;
}

const rules = reactive<FormRules>({});
const formRef = ref<FormInstance>();

const submit = useAsyncData(
  props.type === 'edit'
    ? `update-system-user-${route.params.uid}`
    : `add-system-user`,
  () =>
    $fetchApi(
      props.type === 'edit'
        ? `/system/user/${route.params.uid}`
        : '/system/user',
      {
        method: props.type === 'edit' ? 'put' : 'post',
        body: user.data.value,
      },
    ),
  {
    immediate: false,
  },
);
submit.pending.value = false;
watchAsyncDataError(submit);

async function onSubmit() {
  if (!formRef.value) return;
  const isValid = await formRef.value.validate().catch(() => false);
  if (!isValid) return;
  // console.log(user.data.value);
  await submit.execute();
  if (submit.error.value) return;
  router.back();
}

// console.log('🚀 ~ file: [uid].vue:8 ~ user:', user);
</script>

<style scoped></style>
